<template>
  <el-main>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedKeys.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form
        ref="searchRef"
        :model="searchParam"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="searchParam.param.userName"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="searchParam.param.nickName"
            placeholder="请输入昵称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="searchParam.param.mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="searchParam.param.email"
            placeholder="请输入邮箱"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" prop="deleted">
          <el-select
            v-model="searchParam.param.deleted"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="option in USER_STATUS_OPTIONS"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="userName" label="用户名" width="120" />
        <el-table-column prop="nickName" label="昵称" width="120" />
        <el-table-column prop="mobile" label="手机号" width="130" />
        <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
        <el-table-column prop="deleted" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.deleted === 0 ? 'success' : 'danger'">
              {{ row.deleted === 0 ? '正常' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createAt" label="创建时间" width="180" />
        <el-table-column prop="updateAt" label="更新时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleResetPassword(row)"
              :disabled="row.deleted === 1"
            >
              重置密码
            </el-button>
            <el-button 
              :type="row.deleted === 0 ? 'danger' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              {{ row.deleted === 0 ? '删除' : '恢复' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParam.curPage"
          v-model:page-size="searchParam.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="searchParam.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!formData.id">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="formData.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="重置密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input 
            v-model="passwordForm.password" 
            type="password" 
            placeholder="请输入新密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit" :loading="passwordSubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-main>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue';
import { 
  getUserList, 
  addUser, 
  updateUser, 
  deleteUser, 
  deleteUsers,
  resetUserPassword,
  updateUserStatus
} from '@/api/user';
import type { User, UserQuery, UserForm } from '@/api/user/UserModel';
import { USER_STATUS_OPTIONS } from '@/api/user/UserModel';

// 响应式数据
const searchRef = ref<FormInstance>();
const formRef = ref<FormInstance>();
const passwordFormRef = ref<FormInstance>();

// 表格数据
const tableData = ref<User[]>([]);
const loading = ref(false);

// 搜索参数
const searchParam = reactive<UserQuery>({
  curPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  param: {
    userName: '',
    nickName: '',
    mobile: '',
    email: '',
    deleted: undefined
  }
});

// 选中的行
const selectedKeys = ref<number[]>([]);

// 对话框
const dialogVisible = ref(false);
const passwordDialogVisible = ref(false);
const dialogTitle = ref('');
const submitLoading = ref(false);
const passwordSubmitLoading = ref(false);

// 表单数据
const formData = reactive<UserForm>({
  userName: '',
  password: '',
  nickName: '',
  mobile: '',
  email: ''
});

// 密码表单数据
const passwordForm = reactive({
  password: '',
  confirmPassword: ''
});

// 当前操作的用户
const currentUser = ref<User | null>(null);

// 表单验证规则
const formRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
};

// 密码表单验证规则
const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 获取用户列表
const loadUserList = async () => {
  try {
    loading.value = true;
    const response = await getUserList(searchParam);
    tableData.value = response.data.records || [];
    searchParam.total = response.data.total || 0;
    searchParam.pages = response.data.pages || 0;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  searchParam.curPage = 1;
  loadUserList();
};

// 重置
const handleReset = () => {
  searchRef.value?.resetFields();
  // 手动重置搜索参数
  searchParam.param.userName = '';
  searchParam.param.nickName = '';
  searchParam.param.mobile = '';
  searchParam.param.email = '';
  searchParam.param.deleted = undefined;
  searchParam.curPage = 1;
  loadUserList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  searchParam.pageSize = val;
  searchParam.curPage = 1;
  loadUserList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  searchParam.curPage = val;
  loadUserList();
};

// 选择改变
const handleSelectionChange = (selection: User[]) => {
  selectedKeys.value = selection.map(item => item.id);
};

// 添加用户
const handleAdd = () => {
  dialogTitle.value = '添加用户';
  resetForm();
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (data: User) => {
  dialogTitle.value = '编辑用户';
  Object.assign(formData, data);
  dialogVisible.value = true;
};

// 重置密码
const handleResetPassword = (data: User) => {
  currentUser.value = data;
  passwordForm.password = '';
  passwordForm.confirmPassword = '';
  passwordDialogVisible.value = true;
};

// 切换用户状态
const handleToggleStatus = async (data: User) => {
  const action = data.deleted === 0 ? '删除' : '恢复';
  const newStatus = data.deleted === 0 ? 1 : 0;
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户"${data.userName}"吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await updateUserStatus(data.id, newStatus);
    ElMessage.success(`${action}成功`);
    loadUserList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`);
    }
  }
};

// 删除用户
const handleDelete = async (data: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${data.userName}"吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteUser(data.id);
    ElMessage.success('删除成功');
    loadUserList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedKeys.value.length === 0) {
    ElMessage.warning('请选择要删除的用户');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedKeys.value.length} 个用户吗？删除后不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteUsers(selectedKeys.value);
    ElMessage.success('批量删除成功');
    selectedKeys.value = [];
    loadUserList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败');
    }
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    userName: '',
    password: '',
    nickName: '',
    mobile: '',
    email: ''
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    if (formData.id) {
      await updateUser(formData);
      ElMessage.success('更新成功');
    } else {
      await addUser(formData);
      ElMessage.success('添加成功');
    }
    
    dialogVisible.value = false;
    loadUserList();
  } catch (error) {
    ElMessage.error(formData.id ? '更新失败' : '添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 提交密码重置
const handlePasswordSubmit = async () => {
  if (!passwordFormRef.value || !currentUser.value) return;
  
  try {
    await passwordFormRef.value.validate();
    passwordSubmitLoading.value = true;
    
    await resetUserPassword(currentUser.value.id, passwordForm.password);
    ElMessage.success('密码重置成功');
    passwordDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('密码重置失败');
  } finally {
    passwordSubmitLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadUserList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: var(--el-table-row-hover-bg-color);
}
</style>